package com.example.downloaddemo;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

public class TestActivity extends Activity {

	private Button down;
	private Button stop;
	private ProgressBar progress;
	private String url="http://gdown.baidu.com/data/wisegame/4f9b25fb0e093ac6/QQ_220.apk";
	private String path;
	private DownLoader loader;
	private LoadInfo info;
	private Handler handler=new Handler(){
		@Override
		public void handleMessage(Message msg) {
			if(msg.what==0){
				progress.setMax(info.getFilesize());
				progress.setProgress(info.getComplete());
			}
			if (msg.what==1){

				progress.incrementProgressBy(msg.arg1);
				if(progress.getProgress()>=progress.getMax()){
					loader.delete();
					Toast.makeText(TestActivity.this,"下载完成",Toast.LENGTH_SHORT).show();
				}
			}
		}
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.item);
		initView();
		path= Environment.getExternalStorageDirectory().getPath()+"/downloaddemo";
		loader=new DownLoader(url,path,2,this,handler);


		down.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if ("下载".equals(down.getText())){
					new Thread(){
						@Override
						public void run() {
							info=loader.getLoadInfo();
							loader.download();
							handler.sendEmptyMessage(0);
						}
					}.start();

					down.setText("暂停");
				}else {
					loader.pause();
					down.setText("下载");
				}
			}
		});


	}

	private void initView() {
		down= (Button) findViewById(R.id.down);
		stop= (Button) findViewById(R.id.stop);
		progress= (ProgressBar) findViewById(R.id.progress);

	}


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.menu_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();

		//noinspection SimplifiableIfStatement
		if (id == R.id.action_settings) {
			return true;
		}

		return super.onOptionsItemSelected(item);
	}
}
